<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>消消乐</title>  
    <style>  
        .block {  
            position: absolute;  
            width: 50px;  
            height: 50px;  
            display: block;  
        }  
    </style>  
</head>  
<body>  
    <div id="counter">你已点击：0个(不能超过4个)</div>  
    <div id="game-area"></div>  
  
    <script>  
        const gameArea = document.getElementById('game-area');  
        let counter = 0;  
        let maxBlocks = Math.floor(Math.random() * 10) * 3;  
        let redBlocks = [];  
        let blackBlocks = [];  
  
        function createBlock(color, idPrefix, blocks) {  
            const block = document.createElement('div');  
            block.id = `${idPrefix}${blocks.length + 1}`;  
            block.className = 'block';  
            block.style.backgroundColor = color;  
            block.style.top = `${Math.random() * 450 + 50}px`;  
            block.style.left = `${Math.random() * 490 + 10}px`;  
            block.onclick = () => handleClick(block.id, blocks);  
            gameArea.appendChild(block);  
            blocks.push(block.id);  
        }  
  
        function handleClick(id, blocks) {  
            if (++counter >= 4) {  
                alert('失败');  
                counter = 0;  
                return;  
            }  
  
            const blockIds = blocks.filter(blockId => {  
                if (blockId.startsWith(id.substring(0, 4))) {  
                    return true;  
                }  
                return false;  
            });  
  
            if (blockIds.length === 3) {  
                blockIds.forEach(id => {  
                    document.getElementById(id).style.display = 'none';  
                });  
                counter = 0;  
                blocks.length = 0; // 清空数组  
            }  
  
            document.getElementById('counter').textContent = `你已点击：${counter}个(不能超过4个)`;  
        }  
  
        for (let i = 0; i < maxBlocks; i++) {  
            createBlock('rgb(221, 59, 59)', 'red', redBlocks);  
            createBlock('black', 'black', blackBlocks);  
        }  
    </script>  
</body>  
</html>